﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.Data.OracleClient;


namespace CCPSIP.Message
{
    public partial class announcement1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void SendAnnouncementButton_Click(object sender, EventArgs e)
        {
            try
            {
                int kMsgPreviewLength = 20;
                //string kDateTimeFormat = "yyyy/MM/dd HH:mm:ss";
                DateTime reqTime = DateTime.Now;
                
                //【02】取得POST參數，驗證身分
                //
                string SERVICE_ID = "LoginSurvey";//機器人服務ID
                string Password = "XpkCxxdSkfuBF7caVUjZ";    //機器人服務密碼
                //string ChatID = "88238";      //聊天ID(對方帳號或ClientGID)
                List<string> ChatID = GetAllChatIDFromOracle();
                //string PPS_CODE = "23204";  //長春員工編號
                //string MobileNum = "886987775414";//接收方的手機號碼(含國碼)
                string MsgType = "T";//訊息類型
                string message = TextBox1.Text;//訊息全文
                int localPID = -1;//發訊方的本機訊息ID

                RobotServiceInfo rService = RobotKit.getServiceInfo(SERVICE_ID, Password);
                if (rService == null)
                {
                    throw new Exception("ERROR_02: Service Authentication Failed");//服務認證失敗
                }

                if (string.IsNullOrEmpty(message))
                {
                    throw new Exception("ERROR_03: Message cannot be empty");//訊息不可空白
                }

                string ROBOT_ID = rService.ROBOT_ID;


                //【03】檢查UserID
                //
                //if (string.IsNullOrEmpty(ChatID))
                //{
                //    string[] UserIDs;
                //    if (string.IsNullOrEmpty(PPS_CODE))
                //        UserIDs = MySqlKitUser.getUserIDbyMobile(MobileNum);
                //    else
                //        UserIDs = MySqlKitUser.getUserIDbyEmpID(PPS_CODE);

                //    if (UserIDs != null && UserIDs.Length > 0)
                //        ChatID = UserIDs[0];
                //}

                //【04】產生訊息摘要
                //
                string msgPreview = message.Replace("\r\n", " ").Replace("\n", " ");
                if (MsgType == "T")
                {
                    if (msgPreview.Length > kMsgPreviewLength)
                        msgPreview = msgPreview.Substring(0, kMsgPreviewLength - 3) + "...";
                    msgPreview = string.Format("{0}: {1}", rService.ROBOT_CNAME, msgPreview);
                }
                else if (Regex.IsMatch(MsgType, "^Q[1-9A-Z]$"))
                {
                    msgPreview = string.Format("{0} sent you a QR code.", rService.ROBOT_CNAME);
                }
                else
                {
                    throw new Exception("ERROR_05: Message type not support");//不支援的訊息類型
                }


                foreach (string s in ChatID)
                {
                    //【05】儲存訊息
                    //
                    long MsgID = OracleKitMsg.InsertMsgOne(ROBOT_ID, s, MsgType, msgPreview, message, localPID, reqTime);


                    //【06】Log機器人回覆
                    //
                    OracleKitRobot.InsertMsgOneRobot("R", s, ROBOT_ID, SERVICE_ID, MsgID, message, reqTime);
                }

                //【97】通知Push Service
                //
                PushKit.WakePushAsync(PushKit.PushType.Msg);


                foreach (string s in ChatID)
                {
                    //【98】傳送 Windows CCP MSG 通知
                    
                    if (SipKit.isHQMobileExt(s))
                    {
                        MSGKit.SendTextHQAsync(s, msgPreview);
                    }
                }
                
                //【99】回傳結果
                //
                /*
                Dictionary<string, string> resultDict = new Dictionary<string, string>();
                resultDict["MsgID"] = Convert.ToString(MsgID);
                resultDict["MsgTime"] = reqTime.ToString(kDateTimeFormat);

                resp.ContentType = "application/json";
                resp.Charset = null;
                fastJSON.JSON.Instance.Parameters.EnableAnonymousTypes = true;
                resultStr = fastJSON.JSON.Instance.ToJSON(resultDict);
                */ 
            }
            catch (Exception ex)
            {
            //    resp.ContentType = "application/xml";
            //    resultStr = Kit.ChrisKit.Ex2Xml(ex, false);
                ChrisKit.SkipVar(ex);
            }
            finally
            {
                //int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                //resp.AppendHeader("Content-Length", contentLength.ToString());
                //resp.Write(resultStr);
                //resp.Flush();
                //resp.Close();
            }
        }

        public static List<string> GetAllChatIDFromOracle()
        {
            OracleConnection connOracle = new OracleConnection("SERVER=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.52.195)(PORT=1521)))(CONNECT_DATA =(SERVER=DEDICATED)(SID=UNIDB)));uid=SIP_CONTACT;pwd=kizuki33");
            OracleCommand cmd = new OracleCommand("SELECT SIP_NUM FROM REG_USER WHERE STATUS = 'Y'", connOracle);
            connOracle.Open();
            OracleDataReader reader = cmd.ExecuteReader();

            List<string> ReturnSipNumList = new List<string>();
            while (reader.Read())
                ReturnSipNumList.Add(Convert.ToString(reader["SIP_NUM"]));

            reader.Dispose();
            connOracle.Dispose();
            
            return ReturnSipNumList;
        }
    }
}